package sg.edu.nus.iss.vmcs.system;

import sg.edu.nus.iss.vmcs.abstraction.IChangeGiverService;
import sg.edu.nus.iss.vmcs.abstraction.ICoinReceiverService;
import sg.edu.nus.iss.vmcs.abstraction.IDispenseService;
import sg.edu.nus.iss.vmcs.abstraction.ITransactionListener;
import sg.edu.nus.iss.vmcs.abstraction.ITransactionService;
import sg.edu.nus.iss.vmcs.store.Coin;

public class TransactionService implements ITransactionService
{
    ICoinReceiverService coinReceiverService;
    IChangeGiverService changeGiverService;
    IDispenseService dispenseService;

    int selectedItemPrice = 0;
    ITransactionListener listener;
    int totalMoney = 0;
    String selectedItemName = "";
    public TransactionService(ICoinReceiverService coinReceiverService,
	    IChangeGiverService changeGiverService,
	    IDispenseService dispenseService)
    {
	this.coinReceiverService = coinReceiverService;
	this.changeGiverService = changeGiverService;
	this.dispenseService = dispenseService;
    }

    @Override
    public void processMoneyReceived(int money)
    {
	
//	Weight5=42.2
//	Weight4=35.0
//	Weight3=18.5
//	Weight2=10.9
//	Weight1=7.1
	
//	Name5=$1
//	Name4=50C
//	Name3=20C
//	Name2=10C
//	Name1=5C
	Coin c = null;
	switch(money){
	case 100:
	    c = new Coin(money,42.2);
	    break;
	case 50:
	    c = new Coin(money,35.0);
	    break;
	case 20:
	    c = new Coin(money,18.5);
	    break;
	case 10:
	    c = new Coin(money,10.9);
	    break;
	case 5:
	    c = new Coin(money,7.1);
	    break;
	}
	
	coinReceiverService.receive(c);
	totalMoney += money;	
	
	if (totalMoney >= this.selectedItemPrice)
	{	    
	    coinReceiverService.storeCash();
	    coinReceiverService.reset();
	    if (this.listener != null)
	    {
		listener.TransactionCompleted(changeGiverService.giveChange(totalMoney - selectedItemPrice ));
	    }
	    totalMoney = 0;
	}
    }

    @Override
    public void startTransaction(String selectedItemName, int selectedItemPrice)
    {
	this.selectedItemName = selectedItemName;
	this.selectedItemPrice = selectedItemPrice;
    }

    @Override
    public void registerTransactionCompletedListener(
	    ITransactionListener listener)
    {
	this.listener = listener;
    }
    
    @Override
    public void terminateTransaction(){
	
    }
    
    @Override
    public void dispense(){
	dispenseService.dispense();
    }
}
